package com.feihong.txgw.push;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.global.GlobalContents;
import com.feihong.txgw.ui.activity.setting.MessageDetailsActivity;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageHelper;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 1、TXGWPushMessageReceiver 是个抽象类，该类继承了 BroadcastReceiver。<br/>
 * 2、需要将自定义的 TXGWPushMessageReceiver 注册在 AndroidManifest.xml 文件中：
 * <pre>
 * {@code
 *  <receiver
 *      android:name="com.feihong.txgw.push.TXGWPushMessageReceiver"
 *      android:exported="true">
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.ERROR" />
 *      </intent-filter>
 *  </receiver>
 *  }</pre>
 * 3、TXGWPushMessageReceiver 的 onReceivePassThroughMessage 方法用来接收服务器向客户端发送的透传消息。<br/>
 * 4、TXGWPushMessageReceiver 的 onNotificationMessageClicked 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法会在用户手动点击通知后触发。<br/>
 * 5、TXGWPushMessageReceiver 的 onNotificationMessageArrived 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法是在通知消息到达客户端时触发。另外应用在前台时不弹出通知的通知消息到达客户端也会触发这个回调函数。<br/>
 * 6、TXGWPushMessageReceiver 的 onCommandResult 方法用来接收客户端向服务器发送命令后的响应结果。<br/>
 * 7、TXGWPushMessageReceiver 的 onReceiveRegisterResult 方法用来接收客户端向服务器发送注册命令后的响应结果。<br/>
 * 8、以上这些方法运行在非 UI 线程中。
 */
public class TXGWPushMessageReceiver extends PushMessageReceiver {

    private String mRegId;
    private HashMap<String, String> map = new HashMap<>();


    /**
     * 用户点击通知栏时触发
     *
     * @param context
     * @param message
     */
    @Override
    public void onNotificationMessageClicked(final Context context, MiPushMessage message) {
        String messageId = message.getMessageId();
        map.remove(messageId);
        // 点击通知栏之后再次存储map集合长度(更新未读消息数);
        PreferenceTools.putInt(GlobalContents.UNREAD_MSG, map.size());
        Intent intent = new Intent(context, MessageDetailsActivity.class);
        String str = intent.toUri(Intent.URI_INTENT_SCHEME);
        intent.putExtra("id", messageId);
        intent.putExtra(PushMessageHelper.KEY_MESSAGE,message);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 通知消息到达客户端后会在通知栏弹出notification，
     * 这时候消息已经传到PushMessageReceiver继承类的onNotificationMessageArrived方法，
     * 但这时候消息还没有通过PushMessageReceiver继承类的的onNotificationMessageClicked方法传到客户端
     *
     * @param context
     * @param message
     * @Override
     */
    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {
        super.onNotificationMessageArrived(context, message);
        String messageId = message.getMessageId();
        // 根据消息ID为key存储在map集合中
        map.put(messageId, messageId);
        // 一接收到消息就存储map集合的长度(未读消息)
        PreferenceTools.putInt(GlobalContents.UNREAD_MSG, map.size());
//        Log.i("通讯顾问", "小米推送  时间: " + getSimpleDate() + "----点击前未读消息数" + map.size() + "messageID" + map.get(messageId) + "message  " + message.getContent() + ":" + message.getTitle() + ":" + message.getTopic());
    }

    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        // 获取mRegId
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
                LogUtils.i("通讯顾问" + "----mRegId  " + mRegId);
                boolean bresult = PreferenceTools.putString(GlobalContents.REGID, mRegId);
                String userId = UserLoginInfo.getUserId();
                String userPhone = UserLoginInfo.getUserPhone();
                if (userId == null) {
                    userId = "";
                }
                if (userPhone == null) {
                    userPhone = "";
                }
                String sdkVersion = android.os.Build.VERSION.RELEASE; // 系统版本号
                String manufacturer = DeviceUtils.getManufacturer(); // 手机厂商
                String model = DeviceUtils.getModel(); // 手机型号
                // 设备信息
                String phoneStatus = ("{\"sdkversion\":\"" + sdkVersion
                        + "\",\"changjia\":\"" + manufacturer
                        + "\",\"model\":\"" + model + "\"}");
                phoneStatus = phoneStatus.replace("\r\n", "");
                phoneStatus = phoneStatus.replace("\n", "");
                // 上传mRegId
                RetrofitManager.getInstance().upLoadRegID(userPhone, mRegId, "1", phoneStatus)
                        .compose(RxHelper.rxSchedulerHelper())
                        .subscribe();
            } else {
            }
        }
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    private static String getSimpleDate() {
        return new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date());
    }

}
